package cn.chencq.collection.array;

public class PersonArray {
	private Person[] arr;

	private int elems;

	public PersonArray() {
		arr = new Person[50];
	}

	public PersonArray(int max) {
		arr = new Person[max];
	}

	public void insert(Person person) {
		arr[elems] = person;
		elems++;
	}

	public void display() {
		for (int i = 0; i < elems; i++) {
			arr[i].display();
		}
		System.out.println();
	}

	public int find(String name) {
		int i;
		for (i = 0; i < elems; i++) {
			if (name.equals(arr[i].getName())) {
				break;
			}
		}

		if (i == arr.length) {
			return -1;
		} else {
			return i;
		}
	}

	public void delete(Person person) {

		if (find(person.getName()) == -1) {
			System.out.println("not find person");
		} else {
			for (int i = find(person.getName()); i < elems; i++) {
				arr[i] = arr[i + 1];
			}
		}
		elems--;
	}

	// ??????
	public void delete(String name) {

		if (find(name) == -1) {
			System.out.println("????????????????????");
		} else {
			for (int i = find(name); i < elems; i++) {
				arr[i] = arr[i + 1];
			}
		}
		elems--;
	}

	// ??????
	public void change(Person oldPerson, Person newPerson) {
		if (find(oldPerson.getName()) == -1) {
			System.out.println("????????????????????");
		} else {
			arr[find(oldPerson.getName())] = newPerson;
		}
	}

	// ???? ???????????
	public void sortByName() {
		int min = 0;
		Person tmp = null;
		for (int i = 0; i < elems - 1; i++) {
			min = i;
			for (int j = i + 1; j < elems; j++) {
				if (arr[j].getName().compareTo(arr[min].getName()) < 0) {
					min = j;
				}
			}
			tmp = arr[i];
			arr[i] = arr[min];
			arr[min] = tmp;
		}
	}

	public void sortByAge() {
		int min = 0;
		Person tmp = null;
		for (int i = 0; i < elems - 1; i++) {
			min = i;
			for (int j = i + 1; j < elems; j++) {
				if (arr[j].getAge() < arr[min].getAge()) {
					min = j;
				}
			}
			tmp = arr[i];
			arr[i] = arr[min];
			arr[min] = tmp;
		}
	}

	public static void main(String[] args) {
		PersonArray pa = new PersonArray();

		Person p1 = new Person("????", 20, "??");
		Person p2 = new Person("????", 30, "??");
		Person p3 = new Person("????", 18, "?");
		Person p4 = new Person("????", 23, "??");
		Person p5 = new Person("???", 25, "??");

		pa.insert(p1);
		pa.insert(p2);
		pa.insert(p3);
		pa.insert(p4);
		pa.insert(p5);

		pa.display();

		pa.delete(p4);
		pa.display();

		pa.delete("???");
		pa.display();

		Person newPerson = new Person("?????", 40, "??");
		pa.change(p1, newPerson);
		pa.display();
		
		pa.sortByName();
		pa.display();

		pa.sortByAge();
		pa.display();

	}
}
